package com.woniuxy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @Author: 马宇航
 * @Todo: 处理文件的上传
 * @DateTime: 22/04/01/0001 下午 3:25
 * @Component: 成都蜗牛学苑
 **/
@Controller
public class FileController {
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, HttpServletResponse response,
            MultipartFile multipartFile) throws IOException {
        //推荐使用七牛云
        //判断文件是否为空
        if (!multipartFile.isEmpty()) {
            //获取上传文件存储路径
            String realPath = request.getSession().getServletContext().getRealPath("/imagic/");
            //上传文件名
            String originalFilename = multipartFile.getOriginalFilename();
            File file = new File(realPath, originalFilename);
            if (!file.getParentFile().exists()){
                //可以创建一个文件夹
                file.getParentFile().mkdirs();
            }
            //用流把文件存储到服务器中
            multipartFile.transferTo(new File(realPath+File.separator+originalFilename));
            return "success";
        }else {
            return "文件不能为空";
        }
    }
}
